package com.ccsu.joysport.service;


import ch.qos.logback.core.util.StringUtil;
import com.ccsu.joysport.controller.model.resp.AdminActivityResp;
import com.ccsu.joysport.dto.*;
import com.ccsu.joysport.entity.*;
import com.ccsu.joysport.repository.*;
import com.ccsu.joysport.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AdminActivityService {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private ActivityRepository activityRepository;

    @Autowired
    private ClubRepository clubRepository;

    @Autowired
    private ManagerRepository managerRepository;

    @Autowired
    private ClubOperatorRepository clubOperatorRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StudentActivityRepository studentActivityRepository;



    public ActivityResponse createActivity(CreateActivityRequest request) {
        // 解析token获取管理员ID
        String adminId = jwtUtil.extractId(request.getAdminToken());
        if (adminId == null) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "token解析失败");
        }

        // 检查俱乐部是否存在
        clubRepository.findById(request.getClubId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "俱乐部未找到"));

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime startDateTime = LocalDateTime.parse(request.getActivityTimeStart(), formatter);
        LocalDateTime endDateTime = LocalDateTime.parse(request.getActivityTimeEnd(), formatter);

        // 创建活动
        Activity activity = new Activity();
        activity.setClubId(request.getClubId());
        activity.setActivityName(request.getActivityName());
        activity.setActivityDesc(request.getActivityDesc());
        activity.setActivityImage(request.getActivityImage());
        activity.setActivityTimeStart(Timestamp.valueOf(startDateTime));
        activity.setActivityTimeEnd(Timestamp.valueOf(endDateTime));
        activity.setActivityMax(request.getActivityMax());
        activity.setActivityOrganizer(adminId);
        activity.setActivityPerson(request.getActivityPerson());
        activity.setActivityPlace(request.getActivityPlace());
        activity.setActivityStatus("wait");
        activity.setCreateUser(adminId);
        activityRepository.save(activity);

        return new ActivityResponse("success", "活动创建成功");
    }


    public ActivityResponse deleteActivity(DeleteActivityRequest request) {
        // 解析token获取管理员ID
        String adminId = jwtUtil.extractId(request.getAdminToken());
        if (adminId == null) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "token解析失败");
        }

        // 根据clubId和activityId查找活动
        Activity activity = activityRepository.findByActivityIdAndClubId(request.getActivityId(), request.getClubId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "活动未找到"));


        // 获取当前服务器时间
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        // 判断当前时间是否在活动开始和结束时间之间
        if (currentTime.after(activity.getActivityTimeStart()) && currentTime.before(activity.getActivityTimeEnd())) {
            return new ActivityResponse("fail", "活动期间不能删除活动");
        }

        // 判断当前时间是否在活动结束后
        if (currentTime.after(activity.getActivityTimeEnd())) {
            return new ActivityResponse("fail", "活动结束后不能删除活动");
        }

        // 删除活动
        activityRepository.delete(activity);
        return new ActivityResponse("success", "活动删除成功");
    }


    public CheckInActivityResponse checkInActivity(CheckInActivityRequest request) {
        // 解析token获取管理员ID
        String adminId = jwtUtil.extractId(request.getAdminToken());
        if (adminId == null) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "token解析失败");
        }

        // 检查活动是否存在
        Activity activity = activityRepository.findById(request.getActivityId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "活动未找到"));

        // 将checkTime转换为ZonedDateTime，确保使用同一时区
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(request.getCheckTime().toString(), formatter);
        ZonedDateTime checkTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));

        // 将活动开始时间和结束时间转换为ZonedDateTime
        ZonedDateTime activityStartTime = activity.getActivityTimeStart().toInstant().atZone(ZoneId.of("Asia/Shanghai"));
        ZonedDateTime activityEndTime = activity.getActivityTimeEnd().toInstant().atZone(ZoneId.of("Asia/Shanghai"));

        // 打印时间信息，用于调试
        System.out.println("活动开始时间: " + activityStartTime);
        System.out.println("活动结束时间: " + activityEndTime);
        System.out.println("签到时间: " + checkTime);

        // 使用ChronoUnit进行时间比较
        long secondsToStart = ChronoUnit.SECONDS.between(activityStartTime, checkTime);
        long secondsToEnd = ChronoUnit.SECONDS.between(checkTime, activityEndTime);

        System.out.println("距活动开始秒数: " + secondsToStart);
        System.out.println("距活动结束秒数: " + secondsToEnd);

        if (secondsToStart >= 0 && secondsToEnd >= 0) {
            // 检查学生是否已经签到
            StudentActivity studentActivity = studentActivityRepository.findByActivityIdAndStudentId(request.getActivityId(), request.getStudentId())
                    .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到报名记录"));

            studentActivity.setActivityState("Y"); // 更新签到状态为已签到
            studentActivityRepository.save(studentActivity);

            return new CheckInActivityResponse("success", "签到成功");
        } else {
            return new CheckInActivityResponse("fail", "不在可签到时间范围内");
        }
    }




    public List<AdminActivityResp> reviewList() {

        List<Activity> activityList = activityRepository.findAll();

        return getAdminActivityResps(activityList);
    }

    private String getUserInfo(student student) {
        if (student == null) {
            return "未找到对应的学生信息";
        }

        return new StringJoiner(" | ")
                .add(student.getStudentNumber())
                .add(student.getCollege())
                .add(student.getName()).toString();
    }


    public ActivityWithClubResponse queryActivity(String activityId) {
        Activity activity = activityRepository.findByActivityId(activityId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "活动未找到"));

        // 获取俱乐部信息
        Club club = clubRepository.findById(activity.getClubId())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到关联的俱乐部"));

        // 格式化时间字段
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String activityTimeStartFormatted = dateFormat.format(activity.getActivityTimeStart());
        String activityTimeEndFormatted = dateFormat.format(activity.getActivityTimeEnd());

        // 创建并返回响应对象
        return new ActivityWithClubResponse(
                activity.getActivityId(),
                activity.getActivityName(),
                activity.getActivityDesc(),
                activity.getActivityImage(),
                activityTimeStartFormatted,
                activityTimeEndFormatted,
                activity.getActivityMax(),
                activity.getActivityOrganizer(),
                activity.getClubId(),
                activity.getActivityPerson(),
                activity.getActivityPlace(),
                club.getCollege(),
                club.getClubName()
        );
    }



    public List<StudentSignupResponse> getSignupStudents(String activityId) {
        List<StudentActivity> studentActivities = studentActivityRepository.findByActivityId(activityId);
        return studentActivities.stream().map(studentActivity -> {
            student student = studentRepository.findByStudentNumber(studentActivity.getStudentId())
                    .orElseThrow(() -> new RuntimeException("未找到学生信息"));
            return new StudentSignupResponse(
                    studentActivity.getStudentId(),
                    studentActivity.getActivityState(),
                    student.getStudentNumber(),
                    student.getName(),
                    student.getCollege(),
                    student.getMajor()
            );
        }).collect(Collectors.toList());
    }

    public List<AdminActivityResp> manageList(String adminId, String searchText, Integer pageNum, Integer pageSize) {
        Optional<Manager> optionalManager = managerRepository.findByAccount(adminId);

        List<String> clubIds;

        if (optionalManager.isPresent()) {
            Manager manager = optionalManager.get();

            String role = manager.getRole();

            if ("super".equals(role)) {
                clubIds = clubRepository.findAll().stream()
                        .map(Club::getClubId).toList();
            } else if ("root".equals(role)) {
                clubIds = clubRepository.findByClubUserName(manager.getName()).stream()
                        .map(Club::getClubId).toList();
            } else {
                throw new RuntimeException("未知的角色权限");
            }
        } else {
            List<ClubOperator> clubOperators = clubOperatorRepository.findByOperatorStudentId(adminId);
            clubIds = clubOperators.stream().map(ClubOperator::getClubId).toList();
        }

        if (StringUtil.isNullOrEmpty(searchText)) {
            searchText = "%";
        } else {
            searchText = "%" + searchText + "%";
        }

        // 过滤已审核通过的活动
        List<Activity> activityList = activityRepository.findByClubIdInAndActivityNameLikeAndActivityStatusEquals(clubIds, searchText, "approve", PageRequest.of(pageNum, pageSize));

        List<AdminActivityResp> responseList = getAdminActivityResps(activityList);

        responseList.forEach(resp -> {
            Activity activity = activityRepository.findById(resp.getActivityId()).orElse(null);
            Timestamp now = new Timestamp(System.currentTimeMillis());
            if (activity != null) {
                if (now.before(activity.getActivityTimeStart())) {
                    resp.setActivitySignStatus("活动报名中");
                } else if (now.after(activity.getActivityTimeEnd())) {
                    resp.setActivitySignStatus("活动已结束");
                } else {
                    resp.setActivitySignStatus("活动进行中");
                }
            }
        });

        return responseList;
    }

    private List<AdminActivityResp> getAdminActivityResps(List<Activity> all) {
        List<String> clubIds = new ArrayList<>();
        List<String> studentNos = new ArrayList<>();

        all.forEach(content -> {
            clubIds.add(content.getClubId());
            studentNos.add(content.getCreateUser());
        });

        List<student> studentList = studentRepository.findBystudentNumberIn(studentNos);

        Map<String, student> stuNoAndInfoMap = studentList.stream().collect(Collectors.toMap(student::getStudentNumber, student -> student));

        List<Club> clubList = clubRepository.findByClubIdIn(clubIds);

        Map<String, Club> clubIdAndClubMap = clubList.stream().collect(Collectors.toMap(Club::getClubId, club -> club));

        return all.stream().map(activity -> {
            AdminActivityResp adminActivityResp = new AdminActivityResp();

            BeanUtils.copyProperties(activity, adminActivityResp);

            adminActivityResp.setActivityTimeStart(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(activity.getActivityTimeStart()));
            adminActivityResp.setActivityTimeEnd(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(activity.getActivityTimeEnd()));
            adminActivityResp.setMaxParticipants(activity.getActivityMax());
            adminActivityResp.setCollege(clubIdAndClubMap.get(activity.getClubId()).getCollege());
            adminActivityResp.setApplyStatus(activity.getActivityStatus());
            adminActivityResp.setApplyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(activity.getGmtCreate()));
            adminActivityResp.setProposer(activity.getActivityOrganizer() + " | " + activity.getActivityPerson());

            student student = stuNoAndInfoMap.get(activity.getCreateUser());
            adminActivityResp.setProposer(getUserInfo(student));
            adminActivityResp.setClubName(clubIdAndClubMap.get(activity.getClubId()).getClubName());

            return adminActivityResp;
        }).collect(Collectors.toList());
    }


    public EditActivityResponse editActivity(EditActivityRequest request) {
    Activity activity = activityRepository.findByActivityId(request.getActivityId())
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到活动"));

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {
        Timestamp startTime = new Timestamp(dateFormat.parse(request.getActivityTimeStart()).getTime());
        Timestamp endTime = new Timestamp(dateFormat.parse(request.getActivityTimeEnd()).getTime());

        activity.setActivityName(request.getActivityName());
        activity.setActivityDesc(request.getActivityDesc());
        activity.setActivityPlace(request.getActivityPlace());
        activity.setActivityTimeStart(startTime);
        activity.setActivityTimeEnd(endTime);
//        activity.setActivityOrganizer(request.getActivityOrganizer());
//        activity.setActivityPerson(request.getActivityPerson());
        activity.setActivityMax(request.getActivityMax());
        activity.setActivityImage(request.getActivityImage());
//      activity.setClubId(request.getClubId());
        activityRepository.save(activity);

        return new EditActivityResponse("success", "活动信息更新成功");

        } catch (ParseException e) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "日期格式错误，应该是 yyyy-MM-dd HH:mm:ss", e);
        }
    }

    public HandleActivityReviewResponse handleActivityReview(HandleActivityReviewRequest request) {
        HandleActivityReviewResponse response = new HandleActivityReviewResponse();

        Optional<Activity> optionalActivity = activityRepository.findByActivityId(request.getActivityId());
        if (optionalActivity.isEmpty()) {
            response.setStatus("error");
            response.setMessage("活动不存在");
            return response;
        }

        Activity activity = optionalActivity.get();

        // 判断并处理活动状态
        if ("wait".equals(activity.getActivityStatus())) {
            if ("approve".equals(request.getActivityStatus())) {
                activity.setActivityStatus("approve");
                activity.setReviewRemark(request.getReviewRemark());
            } else if ("reject".equals(request.getActivityStatus())) {
                activity.setActivityStatus("reject");
                activity.setReviewRemark(request.getReviewRemark());
            } else {
                response.setStatus("error");
                response.setMessage("无效的活动状态");
                return response;
            }

            activityRepository.save(activity);

            response.setStatus("success");
            response.setMessage("审核完成");
        } else {
            response.setStatus("error");
            response.setMessage("活动已处理");
        }

        return response;
    }
}

